import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PubSub from 'pubsub-js';
import './index.css'

class List extends Component {
    // 初始化
    // list 四种状态, welcome users loading err
    state = {
        users: [],
        isWelcome: true,
        isLoading: false,
        err: '',
    };
    
    // List组件订阅消息, 在组件挂载到页面上时就订阅
    componentDidMount() {
        // 第一个参数msg省略, 用__占位
        this.token = PubSub.subscribe('updateList', (__, stateObj) => {
            this.setState(stateObj);
        });
    }

    componentWillUnmount() {
        // 组件即将卸载时取消订阅
        PubSub.unsubscribe(this.token);
    }
    render() {
        const { users, isWelcome, isLoading, err } = this.state;
        // avatar_url头像 html_url主页地址 login用户名 id-id 
        return (
            <div className='album'>
                {
                    isWelcome ? <h2>Welcome to Github Searching System!</h2> :
                        isLoading ? <h2>Loading...</h2> :
                            err ? <h2 style={{ color: 'red' }}>{err}</h2> :
                                // users ? <h2>The user is not found!</h2> :
                                    users.map((userObj) => {
                                        return (
                                            <div className="card" key={userObj.id}>
                                                <a href={`${userObj.html_url}`} target='_blank' rel='noreferrer' className="card-text">
                                                    <img src={`${userObj.avatar_url}`} style={{ width: '100px' }} alt="avatar" />
                                                </a>
                                                <p className="card-text">{userObj.login}</p>
                                            </div>
                                        );
                                    })
                }
            </div>
        );
    }
}

export default List;